package com.rankeiot.core.excel;

import com.rankeiot.core.util.JSONUtil;
import org.sagacity.sqltoy.callback.StreamResultHandler;


import java.io.IOException;
import java.io.OutputStream;

/**
 * 导出json数据
 */
public class JsonExportHandler implements StreamResultHandler {
    private final OutputStream out;
    protected static final byte split=',';
    protected static final byte lsb='[';
    protected static final byte rsb=']';
    private boolean writeHeader=false;
    public JsonExportHandler(OutputStream out){
        this.out=out;
    }
//    public JsonExportHandler(Context ctx){
//        ctx.setHandled(true);
//        ctx.headerSet("Content-Encoding", "gzip");
//        ctx.charset("UTF-8");
//        ctx.contentType("application/json");
//        try {
//            this.out=new GZIPOutputStream(ctx.outputStream());
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//    }

    public void setWriteHeader(boolean writeHeader) {
        this.writeHeader = writeHeader;
    }

    @Override
    public void start(String[] columnsLabels, String[] columnsTypes) {
        write(lsb);
        if(writeHeader){
            JSONUtil.write(out,columnsLabels);
        }
    }

    @Override
    public void consume(Object row, int rowIndex) {
       if(rowIndex>0){
            write(split);
        }
       JSONUtil.write(out,row);
    }
    private void write(byte[] data){
        try {
            out.write(data);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private void write(byte b){
        write(new byte[]{b});
    }
    @Override
    public void end() {
        write(rsb);
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
